import React,{Component} from 'react'
import {nanoid} from 'nanoid'
import {connect} from 'react-redux'
import {addPerson} from '../../redux/actions/person'

class Person extends Component{

  addPerson = ()=>{
    const name = this.nameNode.value
    const age = this.ageNode.value*1
    const person = {id:nanoid(),name,age}
    this.props.addPerson(person)
    this.nameNode.value = ''
    this.ageNode.value = ''
  }

  render(){
    return(
      <div>
        <h2>我是Person组件，上方求和为：{this.props.count}</h2>
        <input ref={c=>this.nameNode = c} type="text" placeholder='请输入姓名'/>
        <input ref={c=>this.ageNode = c} type="text" placeholder='请输入年龄'/>
        <button onClick={this.addPerson}>添加</button>
        <ul>
          {
            this.props.personArr.map(
              personObj => <li key={personObj.id}>姓名：{personObj.name}--年龄：{personObj.age}</li>
            )
          }
        </ul>
      </div>
    )
  }
}

export default connect(
  state => ({
    personArr:state.persons,
    count:state.count
  }),
  {addPerson}
)(Person)
